import request from '@/utils/request'
import type { ApiResponse, Attachment, AttachmentQueryParams, PageResponse } from '@/types/api'

// 附件管理API
export const attachmentApi = {
  // 分页查询附件列表
  getAttachmentPage(params: AttachmentQueryParams): Promise<ApiResponse<PageResponse<Attachment>>> {
    return request({
      url: '/admin/attachment/page',
      method: 'get',
      params,
    })
  },

  // 获取附件详情
  getAttachment(id: number): Promise<ApiResponse<Attachment>> {
    return request({
      url: `/admin/attachment/${id}`,
      method: 'get',
    })
  },

  // 上传文件
  uploadFile(file: File, siteId: number, userId: number): Promise<ApiResponse<Attachment>> {
    const formData = new FormData()
    formData.append('file', file)
    formData.append('siteId', siteId.toString())
    formData.append('userId', userId.toString())

    return request({
      url: '/admin/attachment/upload',
      method: 'post',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    })
  },

  // 批量上传文件
  batchUploadFiles(files: File[], siteId: number, userId: number): Promise<ApiResponse<Attachment[]>> {
    const formData = new FormData()
    files.forEach(file => {
      formData.append('files', file)
    })
    formData.append('siteId', siteId.toString())
    formData.append('userId', userId.toString())

    return request({
      url: '/admin/attachment/batch-upload',
      method: 'post',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    })
  },

  // 删除附件
  deleteAttachment(id: number): Promise<ApiResponse<void>> {
    return request({
      url: `/admin/attachment/${id}`,
      method: 'delete',
    })
  },

  // 批量删除附件
  batchDeleteAttachments(ids: number[]): Promise<ApiResponse<void>> {
    return request({
      url: '/admin/attachment/batch',
      method: 'delete',
      data: ids,
    })
  },

  // 更新附件使用状态
  updateUsed(id: number, used: number): Promise<ApiResponse<void>> {
    return request({
      url: `/admin/attachment/${id}/used`,
      method: 'put',
      params: { used },
    })
  },
}
